<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class NewYear extends Base
{
    protected $cache_new_year = "NEWYEAR:USER:GIFT:NUM";
    protected $cache_new_year_gift = "NEWYEAR:CONFIG:GIFT:ID";
    protected $cache_new_year_rank = "NEWYEAR:RANK:USER:NUM";
    protected $cache_new_year_click_gift = "NEWYEAR:GIFT:RECEIVE:USER";
    protected $cache_user_pk = "PK:USER:RAMk";


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function cacheGift($gift_id)
    {
        $cache = Redis::GET($this->cache_new_year_gift);
        do {
            if ($cache) {
                break;
            }
            if (empty($gift_id)) break;
            Redis::SET($this->cache_new_year_gift, $gift_id);
            $cache = Redis::GET($this->cache_new_year_gift);
            break;
        } while (false);
        return $cache;
    }

    public function UserGiftIncNum($user_id, $gift_id, $num)
    {
        return Redis::HINCRBY($this->cache_new_year . $gift_id, $user_id, $num);
    }

    public function getUserGiftMin($user_id, $cache_gift)
    {
        if(empty($cache_gift))return [0];
        $cache_gift = explode(',', $cache_gift);
        $cache_gift_num[$cache_gift[0]] = Redis::HGET($this->cache_new_year . $cache_gift[0], $user_id) ?? 0;
        $cache_gift_num[$cache_gift[1]] = Redis::HGET($this->cache_new_year . $cache_gift[1], $user_id) ?? 0;
        $cache_gift_num[$cache_gift[2]] = Redis::HGET($this->cache_new_year . $cache_gift[2], $user_id) ?? 0;
        return $cache_gift_num;
    }

    public function getUserScore($user_id)
    {
        return Redis::ZSCORE($this->cache_new_year_rank, $user_id) ?? 0;
    }

    public function incUserRank($user_id, $score)
    {
        return Redis::zincrby($this->cache_new_year_rank, $score, $user_id);
    }

    public function getGiftNumRank()
    {
        return $rank = Redis::zrevrange($this->cache_new_year_rank, 0, 49, 'WITHSCORES');
    }

    public function receiveGift($user_id,$gift_id)
    {
      return Redis::HSET($this->cache_new_year_click_gift,$user_id,$gift_id);
    }

    public function getReceive($user_id)
    {
        return Redis::HGET($this->cache_new_year_click_gift,$user_id);
    }

    public function setUserPkRank($user_id,$score)
    {
        $cache_key = $this->cache_user_pk . date('ymd');
        Redis::expire($cache_key, 86400 * 7);
        return Redis::zincrby($cache_key, $score, $user_id);
    }

    public function getUserRank()
    {
        $cache_key = $this->cache_user_pk . date('ymd');
        return $rank = Redis::zrevrange($cache_key, 0, 49, 'WITHSCORES');
    }

    public function getUserPkScore($user_id)
    {
        $cache_key = $this->cache_user_pk . date('ymd');
        return Redis::ZSCORE($cache_key, $user_id);
    }


}